package net.hn.hnms.config;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.config.CronTask;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 智呈物联 pan'sx
 * 2023/10/20 13:49
 * 1.0 version
 */
@Component
public class CronTaskRegistrar  implements DisposableBean {
    private final Map<Runnable, ScheduledTask> scheduledTaskMap = new ConcurrentHashMap<>(16);
    @Autowired
    private TaskScheduler taskScheduler;
    /**
     * 新增定时任务
     * @param task
     * @param cron
     */
    public void addTask(Runnable task, String cron) {
        addTask(new CronTask(task, cron));
    }
    public void addTask(CronTask cronTask) {
        if(cronTask != null) {
            Runnable task = cronTask.getRunnable();
            if(this.scheduledTaskMap.containsKey(task)) {
                removeCronTask(task);
            }
            this.scheduledTaskMap.put(task, scheduledCronTask(cronTask));
        }
    }
    /**
     * 移除定时任务
     * @param task
     */
    public void removeCronTask(Runnable task) {
        System.out.println("清除定时任务"+task);
        ScheduledTask scheduledTask = this.scheduledTaskMap.remove(task);
        if(scheduledTask != null) {
            scheduledTask.cancel();
        }
    }
    public ScheduledTask scheduledCronTask (CronTask cronTask) {
        ScheduledTask scheduledTask = new ScheduledTask();
        scheduledTask.future = this.taskScheduler.schedule(cronTask.getRunnable(), cronTask.getTrigger());
        return scheduledTask;
    }
    @Override
    public void destroy() throws Exception {
        //项目停止时终止所有的定时任务
        for (ScheduledTask task : this.scheduledTaskMap.values()) {
            task.cancel();
        }
        this.scheduledTaskMap.clear();
    }

}